import { useState, useEffect, ChangeEvent } from "react";
import NotesView from "./view.tsx";
import NotesAPI from "./api.ts";
import Modal from "./components/model/index.tsx";
import { convertToCSVFormat, parseCSVFileContent } from "./utils.ts";

export default function App() {
  const [notes, setNotes] = useState<Note[]>([]);
  const [activeNote, setActiveNote] = useState<Note | undefined>();
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [noteToDelete, setNoteToDelete] = useState<Note | undefined>();
  const [editedNote, setEditedNote] = useState<Note | undefined>();
  const [showSaveModal, setShowSaveModal] = useState(false);

  useEffect(() => {
    refreshNotes();
  }, []);

  const refreshNotes = () => {
    const fetchedNotes = NotesAPI.getAllNotes();
    setNotes(fetchedNotes);

    if (fetchedNotes.length > 0) {
      setActiveNote(fetchedNotes[0]);
    } else {
      setActiveNote(undefined);
    }
  };

  const handleNoteSelect = (noteId: string) => {
    // 存在已编辑的note,先保存
    if (editedNote) {
      handleSaveButtonClick();
    } else {
      const selectedNote = notes.find((note) => note.id === noteId);
      setActiveNote(selectedNote);
    }
  };

  const handleNoteAdd = () => {
    // 先保存
    if (editedNote) {
      handleSaveButtonClick();
    } else {
      const newNote = {
        title: "新建笔记",
        body: "开始记录...",
      } as Note;

      NotesAPI.saveNote(newNote);
      refreshNotes();
    }
  };

  const handleNoteEdit = (title: string, body: string) => {
    if (activeNote) {
      const updatedNote = { ...activeNote, title, body };
      setEditedNote(updatedNote);
      setActiveNote(updatedNote); // 更新 activeNote 的状态
    }
  };

  const handleSaveButtonClick = () => {
    setShowSaveModal(true);
  };

  const handleNoteSave = () => {
    if (editedNote) {
      NotesAPI.saveNote({
        id: editedNote.id,
        title: editedNote.title,
        body: editedNote.body,
      } as Note);
      setEditedNote(undefined);
      refreshNotes();
    }
    setShowSaveModal(false);
  };

  const handleNoteDelete = (noteId: string) => {
    setNoteToDelete(notes.find((note) => note.id === noteId));
    setShowDeleteModal(true);
  };

  const confirmNoteDelete = () => {
    if (noteToDelete) {
      NotesAPI.deleteNote(noteToDelete.id);
      refreshNotes();
    }
    setShowDeleteModal(false);
  };

  const handleModalCancel = () => {
    setEditedNote(undefined);
    setShowDeleteModal(false);
    setShowSaveModal(false);
    const selectedNote = notes.find((note) => note.id === activeNote?.id);
    setActiveNote(selectedNote);
  };

  const handleImportNotes = (event: ChangeEvent<HTMLInputElement>) => {
    const file = event.target?.files![0];
    const reader = new FileReader();
    reader.onload = (e) => {
      const fileContent = e.target?.result as string;
      // 解析文件内容，转换为笔记数组
      const importedNotes = parseCSVFileContent(fileContent) as Note[];
      // 保存导入的笔记
      importedNotes.forEach((note: Note) => {
        NotesAPI.saveNote(note);
      });
      console.log("importedNotes", importedNotes);
      refreshNotes();
    };
    reader.readAsText(file);
  };

  const handleExportNotes = () => {
    const allNotes = NotesAPI.getAllNotes();
    // 将笔记数据转换为csv
    const exportedData = convertToCSVFormat(allNotes);
    const blob = new Blob([exportedData], { type: "text/plain" });
    // 创建下载链接
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = "exported_notes.csv";
    link.click();
    // 释放 URL 对象
    URL.revokeObjectURL(url);
  };

  return (
    <>
      <Modal
        isOpen={showDeleteModal || showSaveModal}
        title={showDeleteModal ? "确认删除" : "确认保存"}
        message={
          showDeleteModal ? "确认要删除该笔记吗？" : "确认要保存修改吗？"
        }
        onConfirm={showDeleteModal ? confirmNoteDelete : handleNoteSave}
        onCancel={handleModalCancel}
      />
      <NotesView
        notes={notes}
        activeNote={activeNote}
        onNoteSelect={handleNoteSelect}
        onNoteAdd={handleNoteAdd}
        onNoteEdit={handleNoteEdit}
        onNoteDelete={handleNoteDelete}
      />
      {editedNote && (
        <div className="save__button-wrapper">
          <button className="save__button" onClick={handleSaveButtonClick}>
            保存
          </button>
        </div>
      )}

      {notes.length === 0 && !editedNote && (
        <div className="import__button-wrapper">
          <button className="import__button">导入笔记</button>
          <input
            className="import__input"
            type="file"
            onChange={handleImportNotes}
          />
        </div>
      )}

      {notes.length > 0 && !editedNote && (
        <div className="export__button-wrapper">
          <button className="export__button" onClick={handleExportNotes}>
            导出笔记
          </button>
        </div>
      )}
    </>
  );
}
